

//
//  ESPhotoTool.m
//  Eyeshot
//
//  Created by admin on 15/7/9.
//  Copyright (c) 2015年 eyeshot. All rights reserved.
//

#import "ESPhotoTool.h"
#import "ESNewPhotoModel.h"
@implementation ESPhotoTool

static FMDatabase *_db;

+ (void)initialize
{
    //1.获取数据库路径
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"ns.sqlite"];
    
    //2.得到数据库
    _db = [FMDatabase databaseWithPath:filePath];
    
    
    //3.创表
    if ([_db open])
    {
        BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_ns_photo(id integer PRIMARY KEY AUTOINCREMENT, photo_dict blob NOT NULL);"];
        if (result) {
            NSLog(@"创建成功");
        }else
        {
            NSLog(@"创表失败");
        }

    }
 
    
    
  
}


//插入
+ (void)insertDataWithArr:(NSArray *)photoDictArray
{
    for (NSDictionary *photoDict in photoDictArray)
    {
        //把字典转化为二进制数据
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:photoDict];
        [_db executeUpdate:@"INSERT INTO t_ns_photo (photo_dict) VALUES (?);",data];
        
    }
}

//查询,得到结果集
+ (NSArray *)queryPhotoArr
{
    FMResultSet *set = [_db executeQuery:@"SELECT * FROM t_ns_photo;"];
    
    NSMutableArray *mutableArr = [NSMutableArray arrayWithCapacity:0];
    while (set.next)
    {
        NSData *photoDictData = [set objectForColumnName:@"photo_dict"];
        NSDictionary *photoDict = [NSKeyedUnarchiver unarchiveObjectWithData:photoDictData];
        ESNewPhotoModel *photoModel = [[ESNewPhotoModel alloc] init];
        [photoModel setValuesForKeysWithDictionary:photoDict];
        [mutableArr addObject:photoModel];
    }
    return mutableArr;
}

//清除
+ (void)clearnPhotoArr
{
    [_db executeUpdate:@"DELETE  FROM t_ns_photo;"];
}

@end
